package cn.xd.security.controller;

import cn.xd.base.application.aop.SyncBuriedPoint;
import cn.xd.common.enums.IBaseEnum;
import cn.xd.common.enums.auth.AppUserTypeEnum;
import cn.xd.common.enums.auth.UserSourceEnum;
import cn.xd.common.response.ResponseResult;
import cn.xd.security.command.PasswordWithVerifyLoginCommand;
import cn.xd.security.command.WxMIniAppLoginCommand;
import cn.xd.security.domain.cache.service.CacheUserDomainService;
import cn.xd.security.token.AdminUserCaptchaToken;
import cn.xd.security.token.CustomerUserWxMiniToken;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : mirzaLin
 * @data : 2023/12/10
 * @description :
 **/
@RestController
@RequestMapping("/login")
public class LoginController {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private CacheUserDomainService cacheUserDomainService;

    /**
     * 后台管理系统账密+验证码登录
     *
     * @param command
     * @return
     */
    @SyncBuriedPoint(remark = "后台管理系统账密+验证码登录")
    @PostMapping("/adminPasswordWithVerifyLogin")
    public ResponseResult<?> adminPasswordWithVerifyLogin(@Valid @RequestBody PasswordWithVerifyLoginCommand command) {
        AdminUserCaptchaToken adminUserCaptchaToken = new AdminUserCaptchaToken(command);
        Authentication authenticate = authenticationManager.authenticate(adminUserCaptchaToken);
        return ResponseResult.success(cacheUserDomainService.cacheUser(authenticate, command.getSource(),
                IBaseEnum.getEnumByCode(command.getType(), AppUserTypeEnum.class).getCode()));
    }

    /**
     * 微信小程序登录
     *
     * @param command
     * @return
     */
    @PostMapping("/customerWxMiniAppLogin")
    public ResponseResult<?> customerWxMiniAppLogin(@Valid @RequestBody WxMIniAppLoginCommand command) {
        CustomerUserWxMiniToken customerUserWxMiniToken = new CustomerUserWxMiniToken(command);
        Authentication authenticate = authenticationManager.authenticate(customerUserWxMiniToken);
        return ResponseResult.success(cacheUserDomainService.cacheUser(authenticate, UserSourceEnum.WX_MINI_APP.getCode(), AppUserTypeEnum.MAIN_CUSTOMER.getCode()));
    }
}
